package cn.hl.hm.controller;

import cn.hl.hm.constants.FileSuffixType;
import cn.hl.hm.constants.UploadConfig;
import cn.hl.hm.service.OrderService;
import cn.hl.hm.util.InfoCode;
import cn.hl.hm.util.OSSUtil;
import cn.hl.hm.util.Result;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/uploadController")
public class UploadController {
	private static Logger logger = Logger.getLogger(UploadController.class);
	@Autowired
	@Qualifier("uploadConfig")
	private UploadConfig uploadConfig;

	@Autowired
	private OSSUtil ossutil;

	/**
	 * @Title: uploadSinglePic
	 * @Description: 单文件上传
	 * @date: 2016年12月28日
	 * @author: 大和
	 * @param file
	 * @param request
	 * @param response
	 * @param modelmap
	 * @return String
	 * @throws
	 */
	@RequestMapping(value = "/uploadSinglePic", method = RequestMethod.POST)
	public String uploadImagePath(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request,
								  HttpServletResponse response, ModelMap modelmap) {
		logger.info("upload file size: " + file.getSize());
		if (file.getSize() > 5024000) {
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
		try {
			String ctxPath = uploadConfig.getShortUrl();
			if(System.getProperty("os.name").toLowerCase().startsWith("win")){
				ctxPath="c:"+ctxPath;
			}
			String filename =  System.currentTimeMillis() + (int) ((Math.random() * 9 + 1) * 1000)
					+ file.getOriginalFilename();
//			File fileOne = new File(ctxPath, filename);
//			if (!fileOne.exists()) {
//				fileOne.mkdirs();
//			}
//			if (yzImage(file.getOriginalFilename())) {
//				file.transferTo(fileOne);
//
//				String allPath = uploadConfig.getLongUrl() + filename;
//
//				Result.ok(allPath, InfoCode.SUCCESS, response);
//				return null;

			if (yzImage(file.getOriginalFilename())) {
//					file.transferTo(fileOne);
				InputStream inputStream = file.getInputStream();

				ossutil.putObject("hm/"+filename, inputStream);
				String allPath = uploadConfig.getLongUrl() +"hm/" +filename;
				Result.ok(allPath, InfoCode.SUCCESS, response);
				return null;
			} else {
				Result.ok(null, InfoCode.FAILURE, response);
				return null;

			}
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;

	}

	private boolean yzImage(String a) {
		boolean flag = false;
		String fileName = a;
		// 获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名
		if (null == a || "null".equals(a)) {
			return flag;
		}
		List<String> fileTypes = fileTypes();
		String ext = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
		// 对扩展名进行小写转换
		ext = ext.toLowerCase();
		if (fileTypes.contains(ext)) { // 如果扩展名属于允许上传的类型，则创建文件
			flag = true;
		}
		return flag;
	}

	private List<String> fileTypes() {
		List<String> a = new ArrayList<>();
		a.add("jpg");
		a.add("jpeg");
		a.add("bmp");
		a.add("gif");
		a.add("png");
		a.add("txt");
		return a;

	}

	@Autowired
	private OrderService orderService;
	@RequestMapping(value = "/uploadExcelForOrder", method = RequestMethod.POST)
	public String uploadExcelForOrder(@RequestParam(value = "file",required = true) MultipartFile file, HttpServletRequest request,
									  HttpServletResponse response, ModelMap modelmap) {
		logger.info("upload file size: " + file.getSize());
		if (file.getSize() > uploadConfig.getUploadExcelMaxSize()) {
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
		try {
			String ctxPath = uploadConfig.getShortUrl();
//			File fileOne=createFile(ctxPath, file);
			if (FileSuffixType.EXCEL.contains(FileSuffixType.EXCEL.getType(),
					FilenameUtils.getExtension(file.getOriginalFilename()))) {
//				file.transferTo(fileOne);
//				String allPath = uploadConfig.getLongUrl() + fileOne.getName();
				Map<String,Object> map=orderService.importOrderExcel(file);
				Result.ok(map,InfoCode.SUCCESS, response);
				return null;
			} else {
				Result.ok(null, InfoCode.FAILURE, response);
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;

	}

	private File createFile(String ctxPath,MultipartFile uploadFile){
		try {
			if(System.getProperty("os.name").toLowerCase().startsWith("win")){
				ctxPath="c:"+ctxPath;
			}
			String filename =  System.currentTimeMillis() + (int) ((Math.random() * 9 + 1) * 1000)
					+ uploadFile.getOriginalFilename();
			File file = new File(ctxPath, filename);
			if (!file.getParentFile().exists()) {
				file.mkdirs();
			}
			return file;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
